package com.boxuegu.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.boxuegu.MainActivity;

public class UtilsHelper {

    /**
     * 判断 SharedPreferences 文件中是否存在要保存的用户名
     *
     * @param context
     * @param userName
     * @return
     */
    public static boolean isExistUserName(Context context, String userName) {
        boolean has_userName = false;
        SharedPreferences sp = context.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
        String spPsw = sp.getString(userName, "");

        if (!TextUtils.isEmpty(spPsw)) {
            has_userName = true;
        }
        return has_userName;
    }

    public static void saveUserInfo(Context context, String userName, String psw) {
        //将密码用 MD5 加密
        String md5Psw = MD5Utils.md5(psw);
        SharedPreferences sp = context.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);

        //获取编辑器对象 editor
        SharedPreferences.Editor edit = sp.edit();
        // 将用户名和密码封装到编辑器对象 editor 中
        edit.putString(userName, md5Psw);
        edit.commit();
    }

    public static void saveLoginStatus(Context context, boolean status, String userName) {
        SharedPreferences sp = context.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
        //获取编辑器对象 editor
        SharedPreferences.Editor edit = sp.edit();
        //存入登录的状态
        edit.putBoolean("isLogin", status);
        // 存入登录的用户名
        edit.putString("loginUserName", userName);
        edit.commit();
    }


    /**
     * 根据用户名读取md5密码
     *
     * @param context
     * @param userName
     * @return
     */
    public static String readPsw(Context context, String userName) {
        SharedPreferences loginInfo = context.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
        String spPsw = loginInfo.getString(userName, "");
        return spPsw;
    }


    public static String readLoginUserName(Context context) {
        SharedPreferences sp = context.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
        String userName = sp.getString("loginUserName", ""); //获取登入时的用户名
        return userName;
    }

    public static boolean readLoginStatus(Context context) {
        SharedPreferences sp = context.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
        boolean isLogin = sp.getBoolean("isLogin", false);
        return isLogin;
    }

    public static void clearLoginStatus(Context context) {
        SharedPreferences sp = context.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("isLogin", false);
        editor.putString("loginUserName", "");
        editor.commit();

    }
}
